/**
 * @Description: 图片上传
 * @Author: rcc
 * @Date: 2024-8-31 16:41:44
 */

import { apiUrl } from '@/configs/index.ts'

interface PathResult {
	filePath : string,
	success : boolean,
}

interface UploadResult {
	url : string,
	path : string,
	success : boolean,
}

export default function useUpload() {
	/**
	 * 选择图片
	 *
	 * @returns {Promise<PathResult>} 图片信息.
	 */
	const chooseImage = () : Promise<PathResult> => {
		return new Promise<PathResult>((resolve) => {
			uni.chooseImage({
				count: 1,
				success(res) {
					resolve({
						success: true,
						filePath: res.tempFilePaths[0],
					})
				},
				fail() {
					resolve({
						filePath: '',
						success: false,
					})
				},
			})
		})
	}

	/**
	 * 上传图片
	 *
	 * @param {string} filePath - 文件路径.
	 * @returns {Promise<UploadResult>} 上传结果.
	 */
	const uploadImage = (filePath : string) : Promise<UploadResult> => {
		return new Promise((resolve) => {
			uni.uploadFile({
				url: `${apiUrl}/upload/index`,
				filePath,
				name: 'file',
				success: (res) => {
					const data = JSON.parse(res.data)

					resolve({
						path: data.data.url,
						url: data.data.fullurl,
						success: true,
					})
				},
				fail() {
					resolve({
						url: '',
						path: '',
						success: false,
					})
				},
			})
		})
	}

	return {
		chooseImage,
		uploadImage,
	}
}
